const app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    screenWidth: getApp().globalData.windowWidth,
    windowHeight: getApp().globalData.windowHeight,
    phonelist: [],//轮播图列表
    pmInfo: [],
    content: '',
    showcont: false,
    bidCompany: '',
    address: '',
    contacts: '',
    contactsTel: '',
    contactsCom:'',
    contactsContent:'',
    showTitleImage: false, // 是否显示new图标
    uuid: '',
    scsj:false, // 是否收藏
    showModal: false,
    weekData: 0,
    leftData: 0,
    current:0, // 轮播图默认第一张
    ip: '124.239.176.230',
    imgUrl: app.data.imgUrl,
    zcMInfo: [],//相关推荐
    keywordArr: [],//标的标签
    countdownTimer: null, // 记录倒计时 
    banner_tips: '',
    imageName1: '', // 有轮播图的时候图片名字
    imageName2: '' ,// 没有轮播图时图片名字
    dor_left:0, // 相关推荐底部滚动条
    scrollViewWidth: 0, // 相关推荐scrollView总长度
    baomingType:'', // 报名方式
    currentPMState: 0, // 当前拍卖状态(0,无状态，1即将开拍，2进行中，3结束)自己定义状态
    showBaoMing: false, // 立即报名
    maxNumber: 0, // textarea输入字数
    lxrName : '', // 联系人名字
    lxPhone : '', // 联系电话
    lxContent : '', // 补充内容
    issy:false, // 是否是生意界面进来的如果是true，不是就是false
    wxpush: '',
    wxopenid: '',
  },

  //监听轮播图的下标
  monitorCurrent: function (e) {
    let current = e.detail.current;
    this.setData({
      current: current,
      bannerType: this.data.phonelist[current].type
    })
  },
  // 倒计时
  timeCountdown: function (e) {
    let bidTenderTime = this.data.pmInfo.bidTenderTime
    let imageName1 = ''
    let imageName2 = ''
    let banner_tips = ''
    // 获取当前的时间戳
    let timestamp = Date.now();
    // 获取后台的时间戳 bidTenderTime
    let api_timestamp = util.timeNumberWithStr(bidTenderTime)
    // 2个时间戳进行对比
    let diffInSeconds = timestamp - api_timestamp;
    // 讲差值转换成小时
    let isMoreThan24Hours = diffInSeconds / (1000 * 60 * 60);
    // pmInfo
    let pmstate = 0
    if (!bidTenderTime) {
      imageName1 = '/images/dd_jlkp.png'
      imageName2 = '/images/d_jlkp.png'
      banner_tips = '拍卖时间待定，请持续关注'
    } else if (isMoreThan24Hours > 24) {
      // 当前时间 > 后台返回的时间，并且都超过了24小时，那肯定已经结束了
      imageName1 = '/images/dd_pmjs.png'
      imageName2 = '/images/d_pmjs.png'
      banner_tips = '招标拍卖已结束'
      pmstate = 3;
    } else if (isMoreThan24Hours >= 0 && isMoreThan24Hours <= 24) {
      // 当前时间 > 后台返回的时间，但是没有超过24小时,状态就代表进行中
      imageName1 = '/images/dd_zzjx.png'
      imageName2 = '/images/d_zzjx.png'
      banner_tips = '实际竞拍进度以拍卖平台为准'
      pmstate = 2;
    } else if (isMoreThan24Hours < 0) {
      // 当前时间 < 后台返回时间，并且还有很长时间(大于24小时)才能到达后台返回时间
      imageName1 = '/images/dd_jlkp.png'
      imageName2 = '/images/d_jlkp.png'
      pmstate = 1;
      // 获取时间戳差值
      let diff = api_timestamp - timestamp;
      var that = this
      // 先提前执行1秒
      let diffs = diff - 1000
      // 然后把数据更新出来
      banner_tips = this.daoTime(diffs)
      // 赋值
      this.setData({
        banner_tips: banner_tips,
        imageName1: imageName1,
        imageName2: imageName2
      })
      var timeLong = setInterval(() => {
        // 又过了1秒以后diffs - 1000，再次开始倒
        that.setData({
          banner_tips: that.daoTime(diffs - 1000),
        })
        // 然后每倒一次就-1000
        diffs -= 1000
      }, 1000);
      // 更新倒计时
      this.setData({
        timeLong: timeLong,
      })
    }
     // 赋值
     this.setData({
      banner_tips: banner_tips,
      imageName1: imageName1,
      imageName2: imageName2,
      currentPMState: pmstate
    })
  },
  // 倒计时方法
  daoTime: function (diff) {
    let banner_tips = ''
    if (diff <= 0) {
      banner_tips = '0天 0时 0分 0秒'
      clearInterval(this.data.timeLong);
      this.setData({
        timeLong: null
      })
      return
    }
    banner_tips = util.dateWithtimeNumber(diff)
    return banner_tips
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    that.setData({
      optionsData: options,
      issy : options.issy == 'true' ? true : false
    })

    if (options.wxpush) {
      this.setData({
        wxpush: options.wxpush
      })
    }
    if (options.wxopenid) {
      this.setData({
        wxopenid: options.wxopenid
      })
    }

    wx.request({
      url: 'https://zsbpt.zaisubao.cn/index.php/Api/Feijiu/getIp',
      data: {
      },
      method: 'get',
      success: function (r) {
        wx.hideLoading()
        that.setData({
          ip: r.data.ip
        })
        that.lookAuction2()
      },
      fail: function(err) {
        wx.hideLoading()
      }
    });

    var FjLoginLog = wx.getStorageSync('FjLoginLog');
    if (FjLoginLog) {
      console.log('FjLoginLog')
      that.setData({
        islogInActive: true
      })
    } else {
      console.log('!!FjLoginLog')
      that.setData({
        islogInActive: false
      })
    }
    if (app.checkFjLogin()) {
      var LoginUID = FjLoginLog.UID;
    } else {
      var LoginUID = 0;
    }
    var api_input = { uuid: options.uuid, IP: this.data.ip, LoginUID: LoginUID }
   
    this.setData({
      uuid: options.uuid,
    })
    
    this.getInfoMessage()

    // var api_input = {uuid:'0a2177a583074a8a906ae4f93a6b1939'}
    // app.getDaoPostJp('api/BulletinService/bulletin_Get_Info',api_input,function (r) {    
    //   if (r.code == 200) {
    //     console.log(r)
    //     // r.data[0].bidTenderTime = app.formatTime(r.data[0].bid_tender_time,'Y-M-D h:m:s')
    //     if (app.getCurrentDate() < r.data[0].endTime) {
    //       r.data[0].bmstatus =1;
    //     }else{
    //       r.data[0].bmstatus =0;
    //     }   
    //     that.setData({
    //       pmInfo:r.data[0]
    //     })
    //   }
    // })
  },
  lookAuction2() {
    wx.showLoading({
      title: '加载中',
    })
    let that = this
    var FjLoginLog = wx.getStorageSync('FjLoginLog');
    var LoginUID = FjLoginLog.UID;
    var api_input = { uuid: that.data.optionsData.uuid, IP: that.data.ip, LoginUID: LoginUID,isbusiness:this.data.issy ? 1 : '' }
    if (this.data.wxpush && this.data.wxpush != undefined && this.data.wxpush != '') {
      api_input['wxpush'] = this.data.wxpush
    }

    if (this.data.wxopenid && this.data.wxopenid != undefined && this.data.wxopenid != '') {
      api_input['wxopenid'] = this.data.wxopenid
    }

    app.getDaoPostJp('api/BulletinService/bulletin_Get_Info2022', api_input, function (r) {
      wx.hideLoading()    // 查详情
      if (r.code == 200) {
        if (app.getCurrentDate() < r.data.info[0].endTime) {
          r.data.info[0].bmstatus = 1;
        } else {
          r.data.info[0].bmstatus = 0;
        }
        var imageurl = r.data.info[0].bulletinImg;
        const isContained = imageurl.includes('|');
        var imgArr = []
        if (imageurl !== "") {
          if (isContained) {
            imgArr = imageurl.split('|');
          } else {
            imgArr = [imageurl]
          }
        } else {
          imgArr = []
        }
        // 报名截止时间
        // let years = new Date(r.data.info[0].endTime).getFullYear()
        // let month = new Date(r.data.info[0].endTime).getMonth()
        // let day = new Date(r.data.info[0].endTime).getDate()
        // let time = r.data.info[0].endTime.split(' ')[1]
        // r.data.info[0].deadline = month + 1 + '月' + day + '日' + time.slice(0, 5)
        // 开标时间
        // let month2 = new Date(r.data.info[0].bidTenderTime).getMonth()
        // let day2 = new Date(r.data.info[0].bidTenderTime).getDate()
        // let time2 = r.data.info[0].bidTenderTime.split(' ')[1]
        // r.data.info[0].openBidTime = month2 + 1 + '月' + day2 + '日' + time2.slice(0, 5)
        // 标的标签
        var keywordarr = []
        if (r.data.info[0].key_word != "") {
          let key_wordStr =  r.data.info[0].key_word
          keywordarr = that.detectAndSplit(key_wordStr)
        }
        // 200和44是cell的宽度和间距
        let scrollViewWidth = (200 + 44) * r.data.tjdata.length - 44
        that.setData({
          pmInfo: r.data.info[0],
          phonelist: imgArr,
          zcMInfo: r.data.tjdata,
          keywordArr: keywordarr,
          scrollViewWidth : scrollViewWidth,
          scsj:r.data.issc == 0  ? false : true,
          showTitleImage : util.getCurrtDate() == r.data.info[0].releaseTime ,
          baomingType: r.data.bmtype
        })
        that.timeCountdown()
      }
    })
  },
   detectAndSplit(str) {  
    let commaSplit = str.split(',');  
    let pipeSplit = str.split('，');  
    // 假设我们认为更“合理”的分割是产生更多非空字符串的分割  
    if (commaSplit.length > 1 && commaSplit.filter(s => s.trim() !== '').length >= pipeSplit.filter(s => s.trim() !== '').length) {  
        // 使用英文逗号分割  
        return commaSplit;  
    } else {  
        // 使用中文逗号分割  
        return pipeSplit;  
    }  
} ,
  bindchangeScroll(e) {
    // 获取scroller的偏移量*2转换rpx
    let translateX = e.detail.scrollLeft * 2
    // 获取scrollerview可偏移的距离(总长度- 当前屏幕的宽度),即可以滑动的距离
    // 200是每一个cell的宽度，88是2个44的间距
    let widthOff = this.data.scrollViewWidth - (200  * 3 + 88 )
    // 根据偏移量比例，计算出滑块需要滑动的距离
    // 滑块总长度是160，指示器长度是40，所以可滑动距离是120
    let marginLeft =  translateX * 120 / widthOff 
    // 因为滑动不稳定，marginLeft有可能大于120，如果出现就要限制最高是120
    if (marginLeft > 120) {
        marginLeft = 120
    }
    this.setData({
      dor_left: marginLeft
    })
  },

  previewImage(e) {
    let that = this
    wx.previewImage({
      current: e.currentTarget.dataset.img, // 当前显示图片的http链接
      urls: that.data.phonelist // 需要预览的图片http链接列表
    })
  },
  toF5() {
    this.lookAuction2()
    this.setData({
      islogInActive: true
    })
  },
  lookAuction: function () {
    if (app.checkFjLogin()) {
      if (!this.data.showcont) {
        var FjLoginLog = wx.getStorageSync('FjLoginLog');
        var that = this;
        var api_input = {
          LoginUID: FjLoginLog.UID,
          UPwd: FjLoginLog.UPwd,
          InfoID: this.data.pmInfo.uuid,
          UserIP: this.data.ip,
          DoAction: 1,
          InfoZID: this.data.pmInfo.zid,
          isbusiness: this.data.issy ? 1 : ''
        }
        // console.log(api_input, '查看联系方式')
        app.getDaoPostJp('api/BulletinService/bulletin_Get_InfoContact', api_input, function (r) {
          if (r.code == 200) {
            if (r.data.ErrNum == 11) {
              let dd = r.data.InfoContent;
              dd = dd.replaceAll("http://", "https://")
              WxParse.wxParse('dd', 'html', dd, that, 5);
              that.setData({
                showcont: true,
                contacts: r.data.LinkMan,
                contactsTel: r.data.LinkTel,
                contactsCom:r.data.ComName,
                contactsContent: r.data.InfoContent
              })
              wx.pageScrollTo({
                selector: '.materialInfo'
              })
            }
            if (r.data.ErrNum == 2) {
              app.tishikuang('对不起,您没有权限查看该公告,请升级您的会员类型!')
            }
            if (r.data.ErrNum == 4) {
              app.tishikuang('对不起,您本周的查看条数已经用完了!')
            }
            if (r.data.ErrNum == 3) {
              that.setData({
                showModal: true,
                weekData: r.data.AllLookNum,
                leftData: r.data.HaveLookNum
              })
            }
            if (r.data.ErrNum == 9999) {
              app.tishikuang('您密码已修改，请重新登录后查看！');

            }
          }
        })
      }else {
        wx.pageScrollTo({
          selector: '.materialInfo',
        })
      }
      
    } else {
      wx.navigateTo({ url: '../../pages/login/index' });
    }
  },
  cellTap(e){
    let uuid = e.currentTarget.dataset.index
    wx.navigateTo({
      url: '/pages/zhaobiaogonggao/detailed?uuid=' + uuid,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  toBmView: function (e) {
    if (!app.checkFjLogin()) {
      app.tishi('您还没有登录，请先登录')
      return
    }
    
    if (this.data.pmInfo.endTime) {
      var newDateStr = this.data.pmInfo.endTime.replace(/-/g, '/');
      var hout = new Date(newDateStr).getTime() 
      var now =  new Date().getTime() 
      if (hout > now) {
        // 可以报名
        this.setData({
          showBaoMing : true,
        })
      }else {
        // 不可以报名
        app.tishikuang('当前状态不能报名')
      }
    }else {
      // 可以报名
      this.setData({
        showBaoMing : true,
      })
    }
    
  },
  // 获取当前报名信息
  getInfoMessage() {
    if (app.checkFjLogin()) {
      var FjLoginLog = wx.getStorageSync('FjLoginLog');
      app.getDaoPost('api/FeijiuApp/Post_FJ_UserInfoByUID', { uid: FjLoginLog.UID, upwd: FjLoginLog.UPwd }, (res) => {
        if (res.code == 200) {
          var infoDic = JSON.parse(app.aesDec(res.data));
          this.setData({
            lxrName:  infoDic.Uinfo[0].Linkman,
            lxPhone:  infoDic.Uinfo[0].Mobile,
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.lookAuction2()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.timeLong) {
      clearInterval(this.data.timeLong);
      this.setData({
        timeLong: null
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var shareObj = {
      title: this.data.pmInfo.bidName,
      path: '/pages/zhaobiaogonggao/detailed?uuid=' + this.data.uuid,
      imgUrl: '',
    };
    return shareObj;
  },

  onCancel: function () {
    this.setData({
      showModal: false
    })
  },

  onConfirm: function () {
    this.setData({
      showModal: false
    })
    var FjLoginLog = wx.getStorageSync('FjLoginLog');
    var that = this;
    var api_input = {
      LoginUID: FjLoginLog.UID,
      UPwd: FjLoginLog.UPwd,
      InfoID: this.data.pmInfo.uuid,
      UserIP: this.data.ip,
      DoAction: 2,
      InfoZID: this.data.pmInfo.zid,
      platform_type: 4,
      isbusiness: this.data.issy ? 1 : ''
    }
    console.log(api_input, '查看联系方式')
    app.getDaoPostJp('api/BulletinService/bulletin_Get_InfoContact', api_input, function (r) { // 查看联系方式
      if (r.code == 200) {
        if (r.data.ErrNum == 1) {
          var dd = r.data.InfoContent;
          dd = dd.replaceAll("http://", "https://")
          WxParse.wxParse('dd', 'html', dd, that, 5);
          that.setData({
            showcont: true,
            contacts: r.data.LinkMan,
            contactsTel: r.data.LinkTel,
            contactsCom:r.data.ComName,
            contactsContent: r.data.InfoContent
          })
          wx.pageScrollTo({
            selector: '.materialInfo'
          })
        }
        if (r.data.ErrNum == 2) {
          app.tishikuang('对不起,您没有权限查看该公告,请升级您的会员类型!')
        }
        if (r.data.ErrNum == 4) {
          app.tishikuang('对不起,您本周的查看条数已经用完了!')
        }
      }
    })
  },
  fuwudianhua: function () {
    wx.makePhoneCall({
      phoneNumber: '0311-87106666'
    })
  },
  //查看附件详情
  wxParseTagATap(e) {
    const url = e.currentTarget.dataset.src;
    let index = url.lastIndexOf('.')
    let filttype = url.slice(index + 1)
    if (['bmp', 'jpg', 'jpeg', 'png', 'gif', 'image'].some(item => item == filttype)) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.previewImage({
        current: url, // 当前显示图片的 http 链接
        urls: [url], // 需要预览的图片 http 链接列表
        success() {
          wx.hideLoading()
        }
      })
    } else if (['mp4'].some(item => item == filttype)) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.previewMedia({
        sources: [
          {
            url: e.currentTarget.dataset.url,
            type: 'video'
          }
        ], // 需要预览的资源列表
        current: 1, // 当前显示的资源序号,
        success() {
          wx.hideLoading()
        }
      })
    } else if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'].some(item => item == filttype)) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.downloadFile({ //下载
        url: url, // 从后端获取的url地址，赋值在标签的data属性上
        success: function (res) {
          const tempFilePath = res.tempFilePath;
          wx.saveFile({ //保存文件到本地
            tempFilePath,
            success(res) {
              const savedFilePath = res.savedFilePath;
              wx.openDocument({ //新开页面打开文档
                filePath: savedFilePath,
                showMenu: true,
                flieType: filttype,
                success: function (res) {
                  wx.hideLoading()
                },
                fail: function (err) {
                  wx.hideLoading()
                  wx.showToast({
                    title: '暂不支持预览',
                    icon: "none"
                  })
                }
              });
            },
          })
        },
        fail: function (err) {
          wx.showToast({
            title: '下载失败',
          })
        }
      })
    }
    //  else {
    //   wx.navigateTo({
    //     url: '../login/toweb?url=' + url,
    //     success: function(res) {
    //       wx.hideLoading()
    //     }
    //   })
    // }
  },
  // 收藏
  collectionClick(e) {
    var FjLoginLog = wx.getStorageSync('FjLoginLog');
    let pmInfo = this.data.pmInfo
    let parame = {
      strUID: FjLoginLog.UID,
      infoID:pmInfo.uuid,
      title: pmInfo.bidName,
      fbdate: pmInfo.releaseTime ? pmInfo.releaseTime : '无',
      kpdate: pmInfo.bidTenderTime,
      bmjddate: pmInfo.endTime ? pmInfo.endTime : "无",
      szdq: pmInfo.bidAddressName ? pmInfo.bidAddressName : "无",
      DoAction: 1,
      InfoZID: pmInfo.zid ,
    }
    app.getDaoPostSearchNew('api/FeijiuApp/MyPmShouC_Add', parame, (item)=>{
        if (item.code == 200) {
          if (item.data == 1) {
            app.tishi('收藏成功')
            this.setData({
              scsj: true
            })
          }else if (item.data == 2) {
            app.tishi('此数据已收藏')
            this.setData({
              scsj: true
            })
          }else if (item.data == 3) {
            app.tishi('取消成功')
            this.setData({
              scsj: false
            })
          }
        }else {
         app.tishi(item.message)
        }
    })
  },
  // 点击此处查看标的公告详情附件
  navNextPage(e) {
    let content = e.currentTarget.dataset.content
    wx.navigateTo({
      url: './htmlparser',
      success: function (res) {
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: content })
      }
    })
  },
  // 拨打电话
  lxfsclick(e) {
    if (this.data.contactsTel) {
      let arr = this.data.contactsTel.split(" ")
      wx.showActionSheet({
        itemList: arr,
        alertText:'拨打电话',
        success:(res)=>{
          wx.makePhoneCall({
            phoneNumber: arr[res.tapIndex],
          })
        },
      })
      
    }else {
      app.tishi('暂无电话号码')
    }
  },
  // 标签点击
  textClick(e) {
    let names = e.currentTarget.dataset.key
    wx.setStorageSync('zbxq_key', names)
    wx.navigateBack()
  },
  preventTouchMove (e) {
      console.log('eeeee', JSON.stringify(e))
  },
  textareaMove(e) {
    console.log('tttttt', JSON.stringify(e))
  },
  // textarea输入的时候调用
  bindinput(e) {
    let length = e.detail.value.length 
    // 最大是200
    if (length >= 200) {
      length = 200
    }
     this.setData({
       maxNumber: length
     })
  },
  // 点击关闭
  closeClick(e) {
    this.setData({
      showBaoMing: false
    })
  },
  // 联系人输入框
  bindblurlxr(e) {
    let name = e.detail.value
    this.setData({
      lxrName: name
    })
  },
  // 联系电话
  bindblurlxdh(e) {
    let name = e.detail.value
    this.setData({
      lxPhone: name
    })
  },
  // 补充内容
  bindblurbcnr(e) {
    let name = e.detail.value
    this.setData({
      lxContent: name
    })
  },
  // 提交
  tjbmBtn(e) {
    let maxcontn = this.data.lxContent.length
    if (!this.data.lxrName) {
      app.tishi('请输入您的真实姓名')
      return
    }else if (!this.data.lxPhone) {
      app.tishi('请输入您的联系电话')
      return
    }else if (maxcontn > 200) {
      app.tishi('补充内容最多为200字')
      return
    }
    var FjLoginLog = wx.getStorageSync('FjLoginLog'); 

    var api_input = {
      uuid: this.data.pmInfo.uuid,
      name: this.data.pmInfo.bidName,
      applyName: this.data.lxrName,
      applyTel: this.data.lxPhone,
      applyContens: this.data.lxContent,
      loginUID: FjLoginLog.UID
    }
    wx.showLoading({
      title: '',
    })
    app.getDaoPostJp('api/BulletinService/bulletin_Add_Apply', api_input, (res)=>{
      app.tishi(res.message)
        if (res.code == 200) {
          this.setData({
            showBaoMing: false
          })
        }
        this.setData({
          maxNumber: 0
        })
    })
  },
  moreClick(e) {
    let arr = this.data.pmInfo.categoryCode.split('、')
    if (arr.length) {
      let className = arr[0]
      let classID = this.data.pmInfo.classid
      let dic = {className: className, classID:classID}
      wx.setStorageSync('detail_classDic', dic)
      wx.navigateBack()
    }
  }

})